package com.runen.infinitemovement.fragment;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.runen.infinitemovement.App;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.activity.DayTaskActivity;
import com.runen.infinitemovement.activity.InviteFriendsActivity;
import com.runen.infinitemovement.activity.LoginActivity2;
import com.runen.infinitemovement.activity.MainActivity;
import com.runen.infinitemovement.activity.MyHozomActivity;
import com.runen.infinitemovement.activity.MyTeamActivityV2;
import com.runen.infinitemovement.activity.MyTheLongMarchRoadActivity;
import com.runen.infinitemovement.activity.PunchCardActivity;
import com.runen.infinitemovement.activity.WeTheLongMarchRoadActivity;
import com.runen.infinitemovement.activity.WebActivity;
import com.runen.infinitemovement.adapter.AdAdapter;
import com.runen.infinitemovement.adapter.ColumnActivityAdapter;
import com.runen.infinitemovement.adapter.HomeMyTeamAdapter1;
import com.runen.infinitemovement.adapter.MyBannerAdapter;
import com.runen.infinitemovement.adapter.MyDynamicStateAdapter;
import com.runen.infinitemovement.adapter.PersenNumberAdapter;
import com.runen.infinitemovement.model.api.ChallengeAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.base.BaseResponseEntity;
import com.runen.infinitemovement.model.entity.ADDataEntity;
import com.runen.infinitemovement.model.entity.AdInfoEntity;
import com.runen.infinitemovement.model.entity.EventBusEntity;
import com.runen.infinitemovement.model.entity.HomeBarrageEntity;
import com.runen.infinitemovement.model.entity.HomeEntityV2;
import com.runen.infinitemovement.model.entity.MZBannerEntity;
import com.runen.infinitemovement.model.entity.TeamMemberDTOBean;
import com.runen.infinitemovement.model.entity.UserEntity;
import com.runen.infinitemovement.model.enums.ActivityCompat;
import com.runen.infinitemovement.model.enums.MZBannerType;
import com.runen.infinitemovement.model.enums.SPCompat;
import com.runen.infinitemovement.steputil.StepUtil;
import com.runen.infinitemovement.tool.ADToWebOrActivityUtil;
import com.runen.infinitemovement.tool.CommonUtil;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.notchtool.NotchTools;
import com.runen.infinitemovement.tool.notchtool.core.NotchProperty;
import com.runen.infinitemovement.tool.notchtool.core.OnNotchCallBack;
import com.runen.infinitemovement.widget.IndicatorSeekBar;
import com.runen.infinitemovement.widget.easybarrage.Barrage;
import com.runen.infinitemovement.widget.easybarrage.BarrageView;
import com.runen.infinitemovement.widget.imageview.RoundedCornersImage;
import com.runen.infinitemovement.widget.popupwind.MedalPoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.JsonUtils;
import com.runen.rxnetlibrary.utils.SharePreferenceUtils;
import com.runen.rxnetlibrary.utils.TimeUtil;
import com.runen.rxnetlibrary.utils.ToastUtils;
import com.youth.banner.Banner;
import com.youth.banner.indicator.RectangleIndicator;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.rl_torch)
    RelativeLayout rlTorch;
    @BindView(R.id.fl_company_long)
    FrameLayout flCompanyLogo;
    @BindView(R.id.rl_top)
    RelativeLayout rlTop;
    @BindView(R.id.iv_map_bg)
    ImageView ivMapBg;
    @BindView(R.id.iv_title_bg)
    ImageView ivTitleBg;
    @BindView(R.id.rv_day_num)
    RecyclerView rvDayNum;
    @BindView(R.id.rv_hour_num)
    RecyclerView rvHourNum;
    @BindView(R.id.rv_minute_num)
    RecyclerView rvMinuteNum;
    @BindView(R.id.ll_time_info)
    LinearLayout llTimeInfo;
    @BindView(R.id.tvSurplusTime)
    TextView tvSurplusTime;
    @BindView(R.id.tv_my_hozom_num)
    TextView tvMyHozomNum;
    @BindView(R.id.tv_team_go)
    TextView tvTeamGo;
    @BindView(R.id.ll_middle)
    LinearLayout llMiddle;
    @BindView(R.id.tv_company_activity_go)
    TextView tvCompanyActivityGo;
    @BindView(R.id.rv_company_activity)
    RecyclerView rvCompanyActivity;
    @BindView(R.id.ll_company_activity)
    LinearLayout llCompanyActivity;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.rv_hozom)
    RelativeLayout rv_hozom;
    @BindView(R.id.iv_day_task)
    ImageView ivDayTask;
    @BindView(R.id.rv_ad)
    RecyclerView rvAd;
    @BindView(R.id.rci_live_streaming)
    RoundedCornersImage rciLiveStreaming;
    @BindView(R.id.rl_bottom_ad)
    RelativeLayout rlBottomAd;
    @BindView(R.id.tv_live_streaming_discrebel)
    TextView tvLiveStreamingDiscrebel;
    @BindView(R.id.iv_shut_alive_streaming)
    ImageView ivShutAliveStreaming;
    @BindView(R.id.tv_my_team_name)
    TextView tvMyTeamName;
    @BindView(R.id.tv_check_my_team_progress)
    TextView tv_check_my_team_progress;
    @BindView(R.id.tv_team_progress_value)
    TextView tvTeamProgressValue;
    @BindView(R.id.tv_my_team_number)
    TextView tvMyTeamNumber;
    @BindView(R.id.indicator_seek_bar_we_long)
    IndicatorSeekBar indicatorSeekBarWeLong;
    @BindView(R.id.rv_my_team)
    RecyclerView rvMyTeam;
    @BindView(R.id.tv_my_team_more)
    TextView tv_my_team_more;
    @BindView(R.id.we_long_road)
    View we_long_road;
    @BindView(R.id.tv_tinders)
    TextView tv_tinders;
    @BindView(R.id.tv_team_name)
    TextView tv_team_name;
    @BindView(R.id.tv_company_name)
    TextView tv_company_name;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.barrageView)
    BarrageView barrageView;
    @BindView(R.id.rl_barrage_view)
    RelativeLayout rl_barrage_view;
    @BindView(R.id.web_view)
    WebView web_view;
    @BindView(R.id.rci_my_team_header)
    RoundedCornersImage rci_my_team_header;
    @BindView(R.id.tv_team_count)
    TextView tv_team_count;
    @BindView(R.id.tv_party_history_date)
    TextView tv_party_history_date;

    private View view;
    private PersenNumberAdapter persenNumberAdapter;
    private PersenNumberAdapter persenNumberAdapter1;
    private PersenNumberAdapter persenNumberAdapter2;

    private ColumnActivityAdapter columnActivityAdapter;
    private MyDynamicStateAdapter companyCircleAdapter;
    private List<String> listNotice = new ArrayList<>();
    private String companyId = "";
    private AdAdapter adAdapter;
    private int steps;
    private HomeMyTeamAdapter1 homeMyTeamAdapter;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home_1, container, false);
            ButterKnife.bind(this, view);
            EventBus.getDefault().register(this);
            initView();
            initData();

            initWebView();
        }
        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            if (barrageView != null)
                barrageView.destroy();
        } else
            initBarrageList();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (barrageView != null)
            barrageView.destroy();
    }

    @Override
    public void onResume() {
        super.onResume();
        initBarrageList();
    }

    private void initWebView() {
        //Android P行为变更，不可多进程使用同一个目录webView，需要为不同进程webView设置不同目录
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(getActivity());
            String packageName = getActivity().getPackageName();
            if (!packageName.equals(processName)) {
                WebView.setDataDirectorySuffix(processName);
            }
        }
        // 设置WebView的客户端
        webSetting(web_view);
        web_view.loadUrl(String.format(Constant.H5_HISTORY_BRIEF, UserAPI.getUserToken()));
        web_view.getSettings();
        web_view.setVisibility(View.GONE);
    }

    private String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return null;
    }

    /**
     * WebView设置参数
     *
     * @param webView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private static void webSetting(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setDomStorageEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptEnabled(true);
        settings.setLoadWithOverviewMode(true);
        settings.setSupportZoom(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAllowFileAccess(true);// 设置允许访问文件数据
        settings.setSupportMultipleWindows(true);
        settings.setBlockNetworkImage(false);//同步请求图片
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

        });
        webView.addJavascriptInterface(new WebActivity.MyJavascriptInterface(), "android");
    }

    private void initBarrageList() {
        new ChallengeAPI().homeBarrage(new BaseResultCallback<HomeBarrageEntity>() {
            @Override
            public void onResponse(HomeBarrageEntity response) {
                if (response != null && response.code == 0) {
                    if (response.data != null && response.data.size() > 0) {
                        rl_barrage_view.setVisibility(View.VISIBLE);
                        if (barrageView != null)
                            barrageView.destroy();
                        List<Barrage> list = new ArrayList<>();
                        for (HomeBarrageEntity.DataBean dataBean : response.data) {
                            String text = dataBean.copywritingA
                                    + " <font color='#ed3f37'>" + dataBean.copywritingB + "<font/> " + dataBean.copywritingC;
                            list.add(new Barrage(text, dataBean.headImgUrl));
                        }
                        barrageView.setBarrages(list);
                    }
                }
            }
        });
    }

    private List<TeamMemberDTOBean.TeamMemberListBean> memberListBeans = new ArrayList<>();

    private int count = 0;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                steps = StepUtil.getTodayStep(App.getInstance());
                Log.e("TAG", "handleMessage: steps " + steps);
                if (count % 3 == 0) {
                    initBanner(steps);
                }
                count++;
                mHandler.sendEmptyMessageDelayed(1, 3000);
            }
            return false;
        }
    });

    private void initView() {
        //适配刘海屏
        NotchTools.getFullScreenTools().translucentStatusBar(getActivity(), new OnNotchCallBack() {
            @Override
            public void onNotchPropertyCallback(NotchProperty notchProperty) {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tvTeamGo.getLayoutParams();
                layoutParams.topMargin = CommonUtil.dp2px(getActivity(), 100);
                tvTeamGo.setLayoutParams(layoutParams);

//                RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) ivTitleBg.getLayoutParams();
//                layoutParams1.topMargin = CommonUtil.dp2px(getActivity(), 20);
//                ivTitleBg.setLayoutParams(layoutParams1);
            }
        });
        initBanner(steps);

        //获取时间
        long currentTime = System.currentTimeMillis();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M.d");
        Date date = new Date(currentTime);
        String res = simpleDateFormat.format(date);
        tv_party_history_date.setText(res);


        mHandler.sendEmptyMessage(1);
        int height = CommonUtil.getStatusBarHeight(getActivity());
        rlTop.setPadding(30, height + 20, 30, 20);
        srl.setOnRefreshListener(this);
        indicatorSeekBarWeLong.setEnabled(false);
        /**
         * 我的队伍
         */
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvMyTeam.setLayoutManager(layoutManager);
        homeMyTeamAdapter = new HomeMyTeamAdapter1(getActivity());
        rvMyTeam.setAdapter(homeMyTeamAdapter);

        /**
         * 总参与人数
         */
        LinearLayoutManager layoutManagerDay = new LinearLayoutManager(getActivity());
        layoutManagerDay.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvDayNum.setLayoutManager(layoutManagerDay);
        persenNumberAdapter = new PersenNumberAdapter(getActivity());
        rvDayNum.setAdapter(persenNumberAdapter);

        LinearLayoutManager layoutManagerHour = new LinearLayoutManager(getActivity());
        layoutManagerHour.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvHourNum.setLayoutManager(layoutManagerHour);
        persenNumberAdapter1 = new PersenNumberAdapter(getActivity());
        rvHourNum.setAdapter(persenNumberAdapter1);
        LinearLayoutManager layoutManagerMinuye = new LinearLayoutManager(getActivity());
        layoutManagerMinuye.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvMinuteNum.setLayoutManager(layoutManagerMinuye);
        persenNumberAdapter2 = new PersenNumberAdapter(getActivity());
        rvMinuteNum.setAdapter(persenNumberAdapter2);

        /**
         * 公司活动
         */
        LinearLayoutManager layoutManager3 = new LinearLayoutManager(getActivity());
        layoutManager3.setOrientation(LinearLayoutManager.VERTICAL);
        rvCompanyActivity.setLayoutManager(layoutManager3);
        columnActivityAdapter = new ColumnActivityAdapter(getActivity());
        rvCompanyActivity.setAdapter(columnActivityAdapter);
        columnActivityAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (columnActivityAdapter.getData().get(position).activeType == 0) {
                    Intent intent = new Intent(getActivity(), WeTheLongMarchRoadActivity.class);
                    intent.putExtra("companyId", companyId);
                    startActivity(intent);
                } else if (columnActivityAdapter.getData().get(position).activeType == 1) {
                    Intent intent = new Intent(getActivity(), MyTheLongMarchRoadActivity.class);
                    intent.putExtra("userId", UserAPI.getUserId());
                    startActivity(intent);
                } else {
                    Intent intent1 = new Intent(getActivity(), WebActivity.class);
                    intent1.putExtra("LINK_URL", String.format(Constant.ACTIVITY_DETAILS_H5,
                            columnActivityAdapter.getData().get(position).activeId, UserAPI.getUserToken()));
                    startActivity(intent1);
                }
            }
        });
        /**
         * 广告信息
         */
        LinearLayoutManager layoutManager2 = new GridLayoutManager(getActivity(), 3);
        rvAd.setLayoutManager(layoutManager2);
        adAdapter = new AdAdapter(getActivity());
        rvAd.setAdapter(adAdapter);

        adAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ADToWebOrActivityUtil.toType(getActivity(), adAdapter.getData().get(position));
            }
        });
    }

    private void initBanner(int steps) {
        if (getActivity() == null || ((MainActivity) getActivity()).isDestroyed()) {
            return;
        }
        List<MZBannerEntity> bannerEntities = new ArrayList<>();
        bannerEntities.add(new MZBannerEntity(MZBannerType.STEP_COUNT, steps));
        bannerEntities.add(new MZBannerEntity(MZBannerType.SPORT));
        bannerEntities.add(new MZBannerEntity(MZBannerType.SHARE_FRIENDS));

        banner.addBannerLifecycleObserver(this)//添加生命周期观察者
                .setAdapter(new MyBannerAdapter(getActivity(), bannerEntities))
                .setLoopTime(3000)
                .setIndicator(new RectangleIndicator(getActivity()));
    }

    private void initData() {
        handler.removeMessages(2);
        srl.setRefreshing(true);
        postAppVersion();
        new ChallengeAPI().onHomeV2(new BaseResultCallback<HomeEntityV2>() {
            @Override
            public void onResponse(HomeEntityV2 response) {
                srl.setRefreshing(false);
                if (response.code == 0) {
                    if (response.data != null) {
                        initBarrageList();
                        SharePreferenceUtils.putString(getActivity(), SPCompat.HOME_ENTITY, JsonUtils.toJson(response));
                        setView(response.data);
                        setTeamData(response.data.teamMemberDTO);
                    }
                } else {
                    if (response.msg.contains("Authenticated")) {
//                        ToastUtils.showShort(response.msg);
                    } else {
                        ToastUtils.showShort(response.msg);
                    }

                }
            }

            @Override
            public void onError(Throwable e, String body) {
                if (!TextUtils.isEmpty(body)) {
                    if (body.contains("Invalid access token")) {
                        UserAPI.clearLogin();
                        startActivity(new Intent(getActivity(), LoginActivity2.class));
                    }
                } else {
                    HomeEntityV2 response = JsonUtils.fromJson(SharePreferenceUtils.getString(getActivity(), SPCompat.HOME_ENTITY), HomeEntityV2.class);
                    if (response != null && response.data != null) {
                        setView(response.data);
                    }
                }
                super.onError(e, body);
                srl.setRefreshing(false);
            }

            @Override
            public void onComplete() {
                super.onComplete();
                srl.setRefreshing(false);
            }
        });
    }

    private void setTeamData(TeamMemberDTOBean teamMemberDTO) {
        memberListBeans.clear();
        if (teamMemberDTO != null) {
            if (teamMemberDTO.leader != null) {
                TeamMemberDTOBean.TeamMemberListBean listBean = new TeamMemberDTOBean.TeamMemberListBean();
                listBean.nickname = "我是队长";
                listBean.userId = teamMemberDTO.leader.userId;
                listBean.createTime = teamMemberDTO.leader.createTime;
                listBean.tinder = teamMemberDTO.leader.tinder;
                listBean.headImgUrl = teamMemberDTO.leader.headImgUrl;
                memberListBeans.add(listBean);
            }
            if (teamMemberDTO.teamMemberList != null && teamMemberDTO.teamMemberList.size() > 0) {
                for (int i = 0; i < teamMemberDTO.teamMemberList.size(); i++) {
                    if (memberListBeans.size() < 6) {
                        memberListBeans.add(teamMemberDTO.teamMemberList.get(i));
                    }
                }
            }

            TeamMemberDTOBean.TeamMemberListBean memberListBean = new TeamMemberDTOBean.TeamMemberListBean();
            memberListBean.userId = "邀请好友";
            memberListBeans.add(memberListBean);
            String text = "等%s人";
            tv_my_team_more.setText(String.format(text, teamMemberDTO.memberCount));

            int tinders = 0;//团队火种数
            if (teamMemberDTO.teamMemberList != null && teamMemberDTO.teamMemberList.size() > 0) {
                for (int i = 0; i < teamMemberDTO.teamMemberList.size(); i++) {
                    tinders += teamMemberDTO.teamMemberList.get(i).tinder;
                }
            }
            //团队加上队长
            tinders += teamMemberDTO.leader.tinder;
            String tindersStr = "团队火种 %s 颗";
            tv_tinders.setText(String.format(tindersStr, tinders));
            tv_team_name.setText(teamMemberDTO.team.companyName);

            homeMyTeamAdapter.setNewInstance(memberListBeans);
            homeMyTeamAdapter.notifyDataSetChanged();
        }
    }

    private void postAppVersion() {
        JSONObject object = new JSONObject();
        try {
            object.put("type", 1);
            object.put("version", CommonUtil.getAppVersionName(getActivity()));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new UserAPI().postAppVersion(object.toString(), new BaseResultCallback<BaseResponseEntity>() {
            @Override
            public void onResponse(BaseResponseEntity response) {

            }
        });
    }

    private int backgroundWidth, backgroundHeight;

    /**
     * @param dataBean
     */
    @SuppressLint("NewApi")
    private void setView(HomeEntityV2.DataBean dataBean) {
        if (null != dataBean) {
            /**
             * 保存用户的userId
             */
            UserEntity userInfo = UserAPI.getUserInfo();
            if (userInfo != null) {
                if (userInfo.data != null) {
                    userInfo.data.userId = dataBean.userId;
                }
            }
            UserAPI.saveUserInfo(userInfo);
            /**
             * top信息
             */
            companyId = dataBean.topTenantId;
            SharePreferenceUtils.putString(getActivity(), "companyId", companyId);

            String hozomNum = "我当前火种 %s 颗";
            tvMyHozomNum.setText(String.format(hozomNum, dataBean.tinderSurplus));
            /**
             * 地图背景
             */
            GlideUtils.loadImage(getActivity(), dataBean.titleImg, ivTitleBg);
            GlideUtils.loadImage(getActivity(), dataBean.backgroundImg, ivMapBg);

            Glide.with(getActivity()).load(dataBean.backgroundImg)
                    .into(new SimpleTarget<Drawable>() {
                        @Override
                        public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                            backgroundWidth = resource.getIntrinsicWidth() / 2;
                            backgroundHeight = resource.getIntrinsicHeight() / 2;
                            /**
                             * 地图信息
                             */
                            ivMapBg.post(new Runnable() {
                                @Override
                                public void run() {
                                    int mapBgHeight = ivMapBg.getMeasuredHeight();
                                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) barrageView.getLayoutParams();
                                    lp.height = mapBgHeight / 2;
                                    barrageView.setLayoutParams(lp);
                                    if (dataBean != null) {
                                        setMapView(dataBean);
                                    }
                                }
                            });
                        }
                    });
            /**
             * 公司信息
             */
            if (dataBean != null) {
                if (!TextUtils.isEmpty(dataBean.topTenantUrl)) {
                    GlideUtils.loadImage(getActivity(), dataBean.topTenantUrl, rci_my_team_header);
                }
                tv_company_name.setText(dataBean.topTenantName);
                String total = "共有%s支队伍";
                tv_team_count.setText(String.format(total, dataBean.companyNumber));
            }

            getAdInfo();

            /**
             * 公司活动
             */
            if (dataBean.recommendActivities != null) {
                if (dataBean.recommendActivities.size() > 0) {
                    columnActivityAdapter.setNewData(dataBean.recommendActivities);
                    columnActivityAdapter.notifyDataSetChanged();
                    for (int i = 0; i < columnActivityAdapter.getData().size(); i++) {
                        if (columnActivityAdapter.getData().get(i).activeName.contains("我的长征")) {
                            columnActivityAdapter.remove(columnActivityAdapter.getData().get(i));
                            columnActivityAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        }
    }


    private ADDataEntity adDataEntity;
    private ADDataEntity adDataEntity1;
    private boolean isShowAd = true;

    private void getAdInfo() {
        /**
         * 广告信息
         */

        AdInfoEntity adInfoEntity = UserAPI.getADInfo();
        if (adInfoEntity != null) {
            if (adInfoEntity.data != null && adInfoEntity.data.size() > 0) {
                List<ADDataEntity> adList = new ArrayList<>();
                for (int i = 0; i < adInfoEntity.data.size(); i++) {
                    if (adInfoEntity.data.get(i).positionCode == 3) {
                        adList.add(adInfoEntity.data.get(i));
                    }
                    if (adInfoEntity.data.get(i).positionCode == 2) {
                        if (isShowAd) {
                            MedalPoppupWindow.getInstance(getActivity(), adInfoEntity.data.get(i)).show();
                            isShowAd = false;
                        }
                    }
                    if (adInfoEntity.data.get(i).positionCode == 5) {
                        adDataEntity = adInfoEntity.data.get(i);
                    }
                    if (adInfoEntity.data.get(i).positionCode == 6) {
                        adDataEntity1 = adInfoEntity.data.get(i);
                    }
                }
                adAdapter.setNewInstance(adList);
            }
        }
        if (adDataEntity != null) {
            rlBottomAd.setVisibility(View.VISIBLE);
            GlideUtils.loadImage(getActivity(), adDataEntity.cover, rciLiveStreaming);
            tvLiveStreamingDiscrebel.setText(adDataEntity.positionName);
        } else {
            rlBottomAd.setVisibility(View.GONE);
        }
        if (adDataEntity1 != null
                && !TextUtils.isEmpty(adDataEntity1.cover)
                && !TextUtils.isEmpty(adDataEntity1.linkUrl)) {
            GlideUtils.loadImage(getActivity(), adDataEntity1.cover, ivDayTask);
        }
    }

    /**
     * 添加公司进度信息在图片上
     */
    private void setMapView(HomeEntityV2.DataBean dataBean) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.view_custom_mark2, null);
        RoundedCornersImage rc_userHeader = view.findViewById(R.id.rc_userHeader);
        TextView tv_company_name = view.findViewById(R.id.tv_company_name);

        flCompanyLogo.removeAllViews();
        int width[] = CommonUtil.getScreenHW(getActivity());
        tvMyTeamName.setText(dataBean.topTenantName);
        tvTeamProgressValue.setText(CommonUtil.Double2position(dataBean.progress * 100) + "%");
        indicatorSeekBarWeLong.setProgress((int) (dataBean.progress * 100));
        indicatorSeekBarWeLong.setDoubleProgress(dataBean.progress * 100);

        float widthP = CommonUtil.px2dp(getActivity(), width[0]);

        float lastLeft = ((float) dataBean.fromLeft) / backgroundWidth * CommonUtil.dp2px(getActivity(), widthP);
        float lastTop = (((float) dataBean.fromTop) / backgroundHeight) * ivMapBg.getHeight();

        GlideUtils.loadImage(getActivity(), dataBean.topTenantUrl, rc_userHeader);
        tv_company_name.setText(dataBean.topTenantName);

        LinearLayout.LayoutParams llLp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        tv_company_name.measure(w, h);

        llLp.setMargins((int) lastLeft - tv_company_name.getMeasuredWidth() / 2,
                (int) lastTop - CommonUtil.dp2px(getActivity(), 33), 0, 0);

        view.setLayoutParams(llLp);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WeTheLongMarchRoadActivity.class);
                intent.putExtra(ActivityCompat.COMPANY_ID, companyId);
                startActivity(intent);
            }
        });
        flCompanyLogo.addView(view);
    }

    long lastTime;
    private int TIME = 3000;
    private int index = 0;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    long now = lastTime - System.currentTimeMillis();
                    if (now > 0) {
                        onPersonNumber(now);
                        handler.sendEmptyMessageDelayed(1, 1000L);
                    } else {
                        handler.removeMessages(1);
                        llTimeInfo.setVisibility(View.GONE);
                        tvSurplusTime.setText("活动已结束");
                    }
                    break;
                case 2:
                    //index是全局的，判断小于list长度，防止数组越界异常
                    if (listNotice.size() == 1) {
                        index = 0;
//                        tvCollegeDiscreble.setText(listNotice.get(index));
                    } else if (index < listNotice.size()) {
                        index++;
                        if (index == listNotice.size()) {
                            index = 0;
                        }
//                        tvCollegeDiscreble.setText(listNotice.get(index));
                        //自己调自己
                        handler.sendEmptyMessageDelayed(2, TIME);
                    } else if (listNotice.size() == 0) {
//                        tvCollegeDiscreble.setText("暂无信息！");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    private void onPersonNumber(long time) {
        List<String> listD = new ArrayList<>();
        List<String> listH = new ArrayList<>();
        List<String> listM = new ArrayList<>();
        String stringD = TimeUtil.formatDay(time);
        for (int i = 0; i < stringD.length(); i++) {
            listD.add(stringD.charAt(i) + "");
        }
        String stringH = TimeUtil.formatHour(time);
        for (int i = 0; i < stringH.length(); i++) {
            listH.add(stringH.charAt(i) + "");
        }
        String stringM = TimeUtil.formatMinute(time);
        for (int i = 0; i < stringM.length(); i++) {
            listM.add(stringM.charAt(i) + "");
        }
        persenNumberAdapter.setNewData(listD);
        persenNumberAdapter1.setNewData(listH);
        persenNumberAdapter2.setNewData(listM);
    }

    @OnClick({R.id.tv_team_go, R.id.rv_hozom,
            R.id.tv_company_activity_go,
            R.id.iv_day_task, R.id.iv_shut_alive_streaming, R.id.rl_bottom_ad, R.id.tv_user_name,
            R.id.tv_check_my_team_progress, R.id.ll_team, R.id.we_long_road,
            R.id.tv_hit_card, R.id.iv_long_school, R.id.ll_party_history, R.id.ll_challenge_square,
            R.id.ll_100_years, R.id.rl_team_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_hit_card:
                startActivity(new Intent(getActivity(), PunchCardActivity.class));
                break;
            case R.id.tv_team_go://邀请好友
                startActivity(new Intent(getActivity(), InviteFriendsActivity.class));
//                startActivity(new Intent(getActivity(), ArmyGroupManagerActivity.class));
//                startActivity(new Intent(getActivity(), IntroduceActivity.class));
                break;
//            case R.id.ll_we_team_progress_go:
//                if (!TextUtils.isEmpty(companyId)) {
//                    Intent weLongRoad = new Intent(getActivity(), WeTheLongMarchRoadActivity.class);
//                    weLongRoad.putExtra("companyId", companyId);
//                    startActivity(weLongRoad);
//                }
//                break;
//            case R.id.tv_team_progress_more:
//                Intent intent = new Intent(getActivity(), CompanyProgressRankActivity.class);
//                startActivity(intent);
//                break;
//            case R.id.ll_college:
//                Intent longCollege = new Intent(getActivity(), LongCollegeActivity.class);
//                startActivity(longCollege);
//                break;
            case R.id.tv_company_activity_go:
                Intent intent1 = new Intent(getActivity(), WebActivity.class);
                intent1.putExtra("LINK_URL", String.format(Constant.ACTIVITY_H5, UserAPI.getUserToken()));
                startActivity(intent1);
                break;
//            case R.id.tv_choiceness_go:
//                Intent companyCircle = new Intent(getActivity(), CompanyCricleActivity.class);
//                startActivity(companyCircle);
//                break;
//            case R.id.tv_choiceness_more:
//                Intent companyCircle2 = new Intent(getActivity(), CompanyCricleActivity.class);
//                startActivity(companyCircle2);
//                break;
//            case R.id.ll_my_long_road_go:
//                Intent myLongRoad = new Intent(getActivity(), MyTheLongMarchRoadActivity.class);
//                myLongRoad.putExtra("userId", UserAPI.getUserId());
//                startActivity(myLongRoad);
//                break;
            case R.id.rv_hozom:
                startActivity(new Intent(getActivity(), MyHozomActivity.class));
                break;
            case R.id.iv_day_task:
                if (adDataEntity1 != null) {
                    ADToWebOrActivityUtil.toType(getActivity(), adDataEntity1);
                } else
                    startActivity(new Intent(getActivity(), DayTaskActivity.class));
                break;
            case R.id.iv_shut_alive_streaming:
                rlBottomAd.setVisibility(View.GONE);
                break;
            case R.id.rl_bottom_ad://直播跳转
                if (adDataEntity != null) {
                    ADToWebOrActivityUtil.toType(getActivity(), adDataEntity);
                }
                break;
//            case R.id.tv_user_name://跳到公司主页
//                Intent companyHome = new Intent(getActivity(), CompanyHomeActivity.class);
//                companyHome.putExtra("CompanyHome", JsonUtils.toJson(topCompanyInfoBean));
//                startActivity(companyHome);
//                break;
//            case R.id.tv_for_progress://步数兑换
//                startActivity(new Intent(getActivity(), StepsForActivity.class));
//                break;
            case R.id.tv_check_my_team_progress:
            case R.id.rl_team_group:
            case R.id.we_long_road:
                if (!TextUtils.isEmpty(companyId)) {
                    Intent weLongRoad = new Intent(getActivity(), WeTheLongMarchRoadActivity.class);
                    weLongRoad.putExtra("companyId", companyId);
                    startActivity(weLongRoad);
                }
                break;
            case R.id.ll_team:
//                startActivity(new Intent(getActivity(), MyTeamActivity.class));
                startActivity(new Intent(getActivity(), MyTeamActivityV2.class));
                break;
//            case R.id.tv_create_team:
//                if (!TextUtils.isEmpty(companyId)) {
//                    LogUtil.e("companyId", companyId);
//                    Intent intentTeam = new Intent(getActivity(), CheckTeamActivity.class);
//                    intentTeam.putExtra("companyId", companyId);
//                    intentTeam.putExtra("type", 1);
//                    startActivity(intentTeam);
//                }
//                break;
            case R.id.ll_party_history://党史上的今天
                Intent intent2 = new Intent(getActivity(), WebActivity.class);
                intent2.putExtra("LINK_URL", String.format(Constant.H5_HISTORY_LIST, UserAPI.getUserToken()));
                startActivity(intent2);
                break;
            case R.id.iv_long_school:
                Intent intent3 = new Intent(getActivity(), WebActivity.class);
                intent3.putExtra("LINK_URL", String.format(Constant.H5_ASK_INDEX, UserAPI.getUserToken()));
                startActivity(intent3);
                break;
            case R.id.ll_100_years:
                Intent intent4 = new Intent(getActivity(), WebActivity.class);
                intent4.putExtra("LINK_URL", String.format(Constant.H5_100_YEARS, UserAPI.getUserToken()));
                startActivity(intent4);
                break;
            case R.id.ll_challenge_square:
                Intent intent5 = new Intent(getActivity(), WebActivity.class);
                intent5.putExtra("LINK_URL", String.format(Constant.H5_CHANLLENGE_SQUARE, UserAPI.getUserToken()));
                startActivity(intent5);
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        barrageView.destroy();
        handler.removeMessages(1);
        handler.removeMessages(2);
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        initData();
        initBarrageList();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
        switch (event.getMsg()) {
            case 99:
            case 100:
            case EventBusEntity.CODE_104:
            case EventBusEntity.CODE_105:
            case EventBusEntity.CODE_106:
                initData();
                break;
            default:
                break;
        }
    }
}
